package com.zyh.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.entity.ResultEntity;
import com.zyh.util.ResponseUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*
         * inMemoryAuthentication 表示在内存中制造假的登陆数据
         * withUser 定义账号
         * password 定义密码 但是SpringSecurity默认加密 如果不想使用加密 需要给密码
         * 添加前缀 {noop} 该前缀是一种声明用于让SpringSecurity知道密码的加密方式 前缀
         * 不参与密码校验
         * roles 是角色 和授权有关系
         */
        auth.inMemoryAuthentication()
                .withUser("xiaohei").password("{noop}123456").roles("admin")
                .and()
                .withUser("xiaoheihei").password("{noop}123456").roles("admin");

    }

    /**
     * HttpSecurity 配置拦截规则 跳转 和 自定义登录页面
     *
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首先设置没有认证的时候的提示信息
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        ResponseUtil.out(response, ResultEntity.error("没有登陆"));
                    }//
                }).and().csrf().disable()  //禁用了跨站点请求伪造保护
                //设置哪些请求不用认证
                .authorizeRequests().antMatchers("/login","/register").permitAll()
                // 其它请求，必须要认证授权后才可以访问到
                .anyRequest().authenticated()
                //设置登陆的请求路径
                .and().formLogin().loginProcessingUrl("/login")
                //登录成功时的处理
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        ResponseUtil.out(response, ResultEntity.ok("登陆成功"));
                    }
                })
                //登录失败时的处理
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                        ResponseUtil.out(response, ResultEntity.error("登陆失败"));
                    }
                });
    }
}